extends CanvasLayer

# 增强型UI系统
# 负责处理游戏界面显示、动画效果和用户交互

# UI元素引用
var health_bar: ProgressBar
var experience_bar: ProgressBar
var level_label: Label
var time_label: Label
var score_label: Label
var weapon_icons = []
var enemy_counter: Label
var boss_health_bar: ProgressBar
var message_container: Control
var level_up_panel: Panel
var game_over_panel: Panel
var pause_menu: Panel
var settings_panel: Panel

# UI状态
var is_level_up_panel_visible: bool = false
var is_game_over: bool = false
var is_paused: bool = false
var is_settings_open: bool = false

# 消息队列
var message_queue = []
var current_message_time: float = 0.0
var message_duration: float = 3.0

# 引用
var player
var level_manager
var game_optimizer

func _ready():
	# 获取UI元素引用
	health_bar = $PlayerStats/HealthBar
	experience_bar = $PlayerStats/ExperienceBar
	level_label = $PlayerStats/LevelLabel
	time_label = $TopInfo/TimeLabel
	score_label = $TopInfo/ScoreLabel
	enemy_counter = $TopInfo/EnemyCounter
	boss_health_bar = $BossHealthBar
	message_container = $MessageContainer
	level_up_panel = $LevelUpPanel
	game_over_panel = $GameOverPanel
	pause_menu = $PauseMenu
	settings_panel = $SettingsPanel
	
	# 获取武器图标
	for i in range(4):
		if has_node("WeaponIcons/Weapon" + str(i+1)):
			weapon_icons.append(get_node("WeaponIcons/Weapon" + str(i+1)))
	
	# 获取引用
	player = get_tree().get_first_node_in_group("player")
	level_manager = get_tree().get_first_node_in_group("level_manager")
	game_optimizer = get_tree().get_first_node_in_group("game_optimizer")
	
	# 初始化UI
	initialize_ui()
	
	# 连接信号
	connect_signals()
	
	# 添加到UI组
	add_to_group("ui")

func _process(delta):
	# 更新UI元素
	update_ui(delta)
	
	# 处理消息队列
	process_message_queue(delta)
	
	# 处理输入
	if Input.is_action_just_pressed("ui_cancel"):
		toggle_pause_menu()

func initialize_ui():
	# 设置初始状态
	boss_health_bar.visible = false
	level_up_panel.visible = false
	game_over_panel.visible = false
	pause_menu.visible = false
	settings_panel.visible = false
	
	# 初始化玩家状态UI
	if player:
		health_bar.max_value = player.max_health
		health_bar.value = player.current_health
		experience_bar.max_value = player.experience_required
		experience_bar.value = player.experience
		level_label.text = "等级: " + str(player.level)
	
	# 初始化武器图标
	update_weapon_icons()
	
	# 初始化关卡信息
	if level_manager:
		update_level_info(level_manager.current_level_type, level_manager.level_difficulty)
		time_label.text = "时间: " + format_time(level_manager.level_time_limit)
	
	# 初始化分数
	score_label.text = "分数: 0"
	
	# 初始化敌人计数器
	enemy_counter.text = "敌人: 0/0"

func connect_signals():
	# 连接玩家信号
	if player:
		if player.has_signal("health_changed"):
			player.connect("health_changed", _on_player_health_changed)
		if player.has_signal("experience_changed"):
			player.connect("experience_changed", _on_player_experience_changed)
		if player.has_signal("level_up"):
			player.connect("level_up", _on_player_level_up)
		if player.has_signal("player_died"):
			player.connect("player_died", _on_player_died)
		if player.has_signal("weapon_changed"):
			player.connect("weapon_changed", _on_weapon_changed)
	
	# 连接关卡管理器信号
	if level_manager:
		if level_manager.has_signal("level_time_updated"):
			level_manager.connect("level_time_updated", _on_level_time_updated)
		if level_manager.has_signal("level_completed_signal"):
			level_manager.connect("level_completed_signal", _on_level_completed)
		if level_manager.has_signal("level_failed_signal"):
			level_manager.connect("level_failed_signal", _on_level_failed)

func update_ui(delta):
	# 更新玩家状态UI
	if player and is_instance_valid(player):
		health_bar.value = player.current_health
		experience_bar.value = player.experience
		level_label.text = "等级: " + str(player.level)
	
	# 更新敌人计数器
	var enemy_spawner = get_tree().get_first_node_in_group("enemy_spawner")
	if enemy_spawner and is_instance_valid(enemy_spawner):
		var enemies_defeated = enemy_spawner.enemies_defeated
		var required_defeats = 0
		
		if level_manager:
			match level_manager.current_level_type:
				level_manager.LevelType.DESERT:
					required_defeats = 50 + (level_manager.level_difficulty * 10)
				level_manager.LevelType.FOREST:
					required_defeats = 60 + (level_manager.level_difficulty * 12)
				level_manager.LevelType.SNOW:
					required_defeats = 70 + (level_manager.level_difficulty * 15)
				_:
					required_defeats = 50
		
		enemy_counter.text = "敌人: " + str(enemies_defeated) + "/" + str(required_defeats)
	
	# 更新Boss血条
	var boss = get_tree().get_first_node_in_group("boss")
	if boss and is_instance_valid(boss):
		if not boss_health_bar.visible:
			boss_health_bar.visible = true
			boss_health_bar.max_value = boss.max_health
		
		boss_health_bar.value = boss.current_health
	else:
		boss_health_bar.visible = false

func process_message_queue(delta):
	# 处理当前消息
	if message_container.visible:
		current_message_time += delta
		if current_message_time >= message_duration:
			# 当前消息显示完毕
			current_message_time = 0.0
			message_container.visible = false
			
			# 检查队列中是否有更多消息
			if message_queue.size() > 0:
				var next_message = message_queue.pop_front()
				show_message_immediate(next_message)
	
	# 如果没有显示消息且队列不为空，显示下一条
	elif message_queue.size() > 0 and not message_container.visible:
		var next_message = message_queue.pop_front()
		show_message_immediate(next_message)

func show_message(text):
	# 将消息添加到队列
	message_queue.append(text)
	
	# 如果当前没有显示消息，立即显示
	if not message_container.visible:
		var message = message_queue.pop_front()
		show_message_immediate(message)

func show_message_immediate(text):
	# 设置消息文本
	var message_label = message_container.get_node("MessageLabel")
	message_label.text = text
	
	# 显示消息容器
	message_container.visible = true
	current_message_time = 0.0
	
	# 播放动画
	var tween = create_tween()
	message_container.modulate.a = 0.0
	tween.tween_property(message_container, "modulate:a", 1.0, 0.3)
	
	# 播放音效
	if game_optimizer:
		game_optimizer.play_sound("message")

func update_level_info(level_type, difficulty):
	# 更新关卡信息
	var level_name = ""
	match level_type:
		0: level_name = "教程"
		1: level_name = "沙漠"
		2: level_name = "森林"
		3: level_name = "雪山"
	
	# 显示关卡信息
	show_message(level_name + "关卡 - 难度: " + str(difficulty))
	
	# 播放对应的背景音乐
	if game_optimizer:
		match level_type:
			0: game_optimizer.play_music("tutorial")
			1: game_optimizer.play_music("desert")
			2: game_optimizer.play_music("forest")
			3: game_optimizer.play_music("snow")

func update_weapon_icons():
	# 更新武器图标
	if player and is_instance_valid(player):
		var weapons = player.weapons
		
		for i in range(weapon_icons.size()):
			if i < weapons.size():
				weapon_icons[i].visible = true
				
				# 设置图标
				var weapon_type = weapons[i].type
				var icon_path = "res://asset/weapons/" + weapon_type + "_icon.png"
				if ResourceLoader.exists(icon_path):
					weapon_icons[i].texture = load(icon_path)
				
				# 设置等级
				var level_label = weapon_icons[i].get_node("LevelLabel")
				if level_label:
					level_label.text = "Lv." + str(weapons[i].level)
			else:
				weapon_icons[i].visible = false

func show_level_up_panel(upgrade_options):
	# 显示升级面板
	level_up_panel.visible = true
	is_level_up_panel_visible = true
	
	# 暂停游戏
	get_tree().paused = true
	
	# 设置升级选项
	var options_container = level_up_panel.get_node("OptionsContainer")
	
	# 清除现有选项
	for child in options_container.get_children():
		child.queue_free()
	
	# 添加新选项
	for i in range(min(upgrade_options.size(), 3)):
		var option = upgrade_options[i]
		
		var option_button = Button.new()
		option_button.text = option.name + "\n" + option.description
		option_button.connect("pressed", _on_upgrade_option_selected.bind(i))
		
		options_container.add_child(option_button)
	
	# 播放音效
	if game_optimizer:
		game_optimizer.play_sound("level_up")

func hide_level_up_panel():
	# 隐藏升级面板
	level_up_panel.visible = false
	is_level_up_panel_visible = false
	
	# 恢复游戏
	get_tree().paused = false

func show_game_over_panel(score):
	# 显示游戏结束面板
	game_over_panel.visible = true
	is_game_over = true
	
	# 暂停游戏
	get_tree().paused = true
	
	# 设置分数
	var score_label = game_over_panel.get_node("ScoreLabel")
	score_label.text = "最终分数: " + str(score)
	
	# 播放音效
	if game_optimizer:
		game_optimizer.play_sound("game_over")

func toggle_pause_menu():
	if is_level_up_panel_visible or is_game_over:
		return
	
	is_paused = !is_paused
	
	if is_paused:
		# 显示暂停菜单
		pause_menu.visible = true
		get_tree().paused = true
		
		# 播放音效
		if game_optimizer:
			game_optimizer.play_sound("pause")
	else:
		# 隐藏暂停菜单和设置面板
		pause_menu.visible = false
		settings_panel.visible = false
		is_settings_open = false
		get_tree().paused = false
		
		# 播放音效
		if game_optimizer:
			game_optimizer.play_sound("unpause")

func toggle_settings_panel():
	is_settings_open = !is_settings_open
	settings_panel.visible = is_settings_open
	
	if is_settings_open:
		# 初始化设置面板
		var master_slider = settings_panel.get_node("MasterVolumeSlider")
		var music_slider = settings_panel.get_node("MusicVolumeSlider")
		var sfx_slider = settings_panel.get_node("SFXVolumeSlider")
		
		if game_optimizer:
			master_slider.value = game_optimizer.master_volume
			music_slider.value = game_optimizer.music_volume
			sfx_slider.value = game_optimizer.sfx_volume
		
		# 播放音效
		if game_optimizer:
			game_optimizer.play_sound("menu_open")
	else:
		# 播放音效
		if game_optimizer:
			game_optimizer.play_sound("menu_close")

func format_time(seconds):
	var minutes = int(seconds) / 60
	var secs = int(seconds) % 60
	return "%02d:%02d" % [minutes, secs]

# 信号处理函数
func _on_player_health_changed(new_health, max_health):
	health_bar.max_value = max_health
	health_bar.value = new_health
	
	# 低生命值警告
	if new_health < max_health * 0.3:
		health_bar.modulate = Color(1.0, 0.3, 0.3)
		
		# 播放低生命值音效
		if game_optimizer and new_health > 0:
			game_optimizer.play_sound("low_health")
	else:
		health_bar.modulate = Color(1.0, 1.0, 1.0)

func _on_player_experience_changed(new_exp, required_exp):
	experience_bar.max_value = required_exp
	experience_bar.value = new_exp
	
	# 播放获得经验音效
	if game_optimizer:
		game_optimizer.play_sound("exp_gain", 0.5)

func _on_player_level_up(new_level, upgrade_options):
	level_label.text = "等级: " + str(new_level)
	show_level_up_panel(upgrade_options)

func _on_player_died():
	show_game_over_panel(0)  # 临时使用0分

func _on_weapon_changed():
	update_weapon_icons()

func _on_level_time_updated(time_left):
	time_label.text = "时间: " + format_time(time_left)
	
	# 时间不足警告
	if time_left < 30:
		time_label.modulate = Color(1.0, 0.3, 0.3)
		
		# 每10秒播放一次警告音效
		if int(time_left) % 10 == 0 and game_optimizer:
			game_optimizer.play_sound("time_warning")
	else:
		time_label.modulate = Color(1.0, 1.0, 1.0)

func _on_level_completed():
	show_message("关卡完成！")
	
	# 播放音效
	if game_optimizer:
		game_optimizer.play_sound("level_complete")

func _on_level_failed():
	show_message("关卡失败！")
	
	# 播放音效
	if game_optimizer:
		game_optimizer.play_sound("level_failed")

func _on_upgrade_option_selected(option_index):
	# 通知玩家选择了升级选项
	if player and is_instance_valid(player):
		player.apply_upgrade(option_index)
	
	# 隐藏升级面板
	hide_level_up_panel()
	
	# 播放音效
	if game_optimizer:
		game_optimizer.play_sound("upgrade_selected")

func _on_resume_button_pressed():
	toggle_pause_menu()

func _on_settings_button_pressed():
	toggle_settings_panel()

func _on_quit_button_pressed():
	# 返回主菜单
	get_tree().paused = false
	get_tree().change_scene_to_file("res://MainMenu.tscn")

func _on_master_volume_changed(value):
	if game_optimizer:
		game_optimizer.set_master_volume(value)

func _on_music_volume_changed(value):
	if game_optimizer:
		game_optimizer.set_music_volume(value)

func _on_sfx_volume_changed(value):
	if game_optimizer:
		game_optimizer.set_sfx_volume(value)
		
		# 播放测试音效
		game_optimizer.play_sound("button_click")

func _on_restart_button_pressed():
	# 重新开始游戏
	get_tree().paused = false
	get_tree().reload_current_scene()

func _on_main_menu_button_pressed():
	# 返回主菜单
	get_tree().paused = false
	get_tree().change_scene_to_file("res://MainMenu.tscn")
